package com.yabushan.form.controller;

import java.security.Security;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yabushan.common.utils.SecurityUtils;
import com.yabushan.common.utils.StringUtils;
import com.yabushan.form.domain.*;
import com.yabushan.form.service.IAutoUserTablesService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yabushan.common.annotation.Log;
import com.yabushan.common.core.controller.BaseController;
import com.yabushan.common.core.domain.AjaxResult;
import com.yabushan.common.enums.BusinessType;
import com.yabushan.form.service.IFormInfosService;
import com.yabushan.common.utils.poi.ExcelUtil;
import com.yabushan.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义表单Controller
 *
 * @author yabushan
 * @date 2021-06-29
 */
@RestController
@RequestMapping("/form/infos")
public class FormInfosController extends BaseController
{

    @Autowired
    private IFormInfosService formInfosService;

    @Autowired
    private IAutoUserTablesService tablesService;

    /**
     * 查询自定义表单列表
     */
    @PreAuthorize("@ss.hasPermi('form:infos:list')")
    @GetMapping("/list")
    public TableDataInfo list(FormInfos formInfos)
    {
        startPage();
        String username = SecurityUtils.getUsername();
        if(!username.equals("admin")){
            formInfos.setCreateBy(username);
        }
        List<FormInfos> list = formInfosService.selectFormInfosList(formInfos);
        return getDataTable(list);
    }



    /**
     * 导出自定义表单列表
     */
    @PreAuthorize("@ss.hasPermi('form:infos:export')")
    @Log(title = "自定义表单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FormInfos formInfos)
    {
        List<FormInfos> list = formInfosService.selectFormInfosList(formInfos);
        ExcelUtil<FormInfos> util = new ExcelUtil<FormInfos>(FormInfos.class);
        return util.exportExcel(list, "infos");
    }

    /**
     * 获取自定义表单详细信息
     */
    @PreAuthorize("@ss.hasPermi('form:infos:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(formInfosService.selectFormInfosById(id));
    }

    /**
     * 新增自定义表单
     */
    @PreAuthorize("@ss.hasPermi('form:infos:add')")
    @Log(title = "自定义表单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FormInfos formInfos)
    {
        return toAjax(formInfosService.insertFormInfos(formInfos));
    }

    /**
     * 修改自定义表单
     */
    @PreAuthorize("@ss.hasPermi('form:infos:edit')")
    @Log(title = "自定义表单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FormInfos formInfos)
    {
        return toAjax(formInfosService.updateFormInfos(formInfos));
    }

    /**
     * 删除自定义表单
     */
    @PreAuthorize("@ss.hasPermi('form:infos:remove')")
    @Log(title = "自定义表单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(formInfosService.deleteFormInfosByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('form:infos:add')")
    @Log(title = "生成数据库表", businessType = BusinessType.INSERT)
    @PostMapping(value = "/createTable/{id}")
    public AjaxResult createTable(@PathVariable("id") Long id)
    {
        //判断用户是否已经超过了最大创建表格的限制
        FormInfos formInfoAll = new FormInfos();
        formInfoAll.setCreateBy(SecurityUtils.getUsername());
        List<FormInfos> formInfosList = formInfosService.selectFormInfosList(formInfoAll);
        Integer size=formInfosList.size();
        //判断是否超过限制
        AutoUserTables autoUserTables=new AutoUserTables();
        autoUserTables.setCreatedBy(SecurityUtils.getUsername());
        AutoUserTables autoUserTables1 = tablesService.selectAutoUserTablesList(autoUserTables).get(0);
        //判断表是否超字段
        if(autoUserTables1.getVipLevel().equals("南瓜籽")){
            if(size>= Constant.NGZ.getCREATE_TABLE_NUM()){
                return AjaxResult.error("您创建的表已超过最大限制,请联系管理员！");
            }
        }else if(autoUserTables1.getVipLevel().equals("南瓜苗")){
            if(size>= Constant.NGM.getCREATE_TABLE_NUM()){
                return AjaxResult.error("您创建的表已超过最大限制,请联系管理员！");
            }
        }else if (autoUserTables1.getVipLevel().equals("南瓜藤")){
            if(size>= Constant.NGT.getCREATE_TABLE_NUM()){
                return AjaxResult.error("您创建的表已超过最大限制,请联系管理员！");
            }
        }else if(autoUserTables1.getVipLevel().equals("南瓜花")){
            if(size>= Constant.NGH.getCREATE_TABLE_NUM()){
                return AjaxResult.error("您创建的表已超过最大限制,请联系管理员！");
            }
        }else if(autoUserTables1.getVipLevel().equals("南瓜树")){
            if(size>= Constant.NGS.getCREATE_TABLE_NUM()){
                return AjaxResult.error("您创建的表已超过最大限制,请联系管理员！");
            }
        }else{
            return AjaxResult.error("您创建的表已超过最大限制,请联系管理员！");
        }



//        if(formInfosList.size()>FormConstant.MAX_CUSTOM_CREATE_TABLE){
//            return AjaxResult.error("您创建的表已超过最大限制,请联系管理员！");
//        }

        FormInfos formInfos = formInfosService.selectFormInfosById(id);
        if(formInfos==null){
            return AjaxResult.error("表单不存在");
        }
        String formStr = formInfos.getFields();
        HashMap hashMap = JSON.parseObject(formStr, HashMap.class);
        JSONArray array = JSONArray.parseArray(hashMap.get("fields").toString());
        List<JimuReportDbField> fields = new ArrayList<>();

        String tableName = "custom_"+id;
        StringBuffer buffer= new StringBuffer();
        buffer.append( "create table "+ tableName + " ( ");
        for(int i=0;i<array.size();i++){
            JSONObject job = array.getJSONObject(i);
            String filedsName = job.get("__vModel__").toString();
            buffer.append(filedsName + " varchar(255), ");
            if(i==array.size()-1){
                buffer.append(FormConstant.tableCreateTime);
            }

            //解析字段木棍从
            JSONObject config__ = JSONObject.parseObject(job.get("__config__").toString());
            //生成报表字段
            JimuReportDbField field = new JimuReportDbField();
            field.setId(StringUtils.getUUID());
            field.setCreateBy(SecurityUtils.getUsername());
            field.setCreateTime(new Date());
            field.setJimuReportDbId("custom_"+formInfos.getId().toString());
            field.setFieldName(filedsName);
            field.setFieldText(config__.getString("label"));
            field.setWidgetType("String");
            field.setOrderNum(i);
            fields.add(field);

        }
        buffer.append(")");


        //生成一个报表
        JimuReport report = new JimuReport();
        report.setId("custom_"+formInfos.getId().toString());
        report.setCode(formInfos.getId().toString());
        report.setName(formInfos.getFormMemo());
        report.setType("datainfo");
        report.setCreateBy(SecurityUtils.getUsername());
        report.setCreateTime(new Date());
        report.setDelFlag(0);
        report.setTemplate(1);

        //生成报表API
        JimuReportDb jimuReportDb = new JimuReportDb();
        jimuReportDb.setId("custom_"+formInfos.getId().toString());
        jimuReportDb.setJimuReportId("custom_"+formInfos.getId().toString());
        jimuReportDb.setCreateBy(SecurityUtils.getUsername());
        jimuReportDb.setCreateTime(new Date());
        jimuReportDb.setDbCode(tableName);
        jimuReportDb.setDbChName(formInfos.getFormMemo());
        jimuReportDb.setDbType("0");
        jimuReportDb.setDbDynSql("select * from "+tableName);
        jimuReportDb.setIsList(1);
        jimuReportDb.setIsPage("1");
        jimuReportDb.setDbSourceType("MYSQL");


        //更新表单状态为已物化
        formInfos.setFormStatus("2");

        formInfosService.createTable(buffer.toString(),formInfos,report,jimuReportDb,fields);
        return AjaxResult.success(1);
    }


}
